#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <signal.h>
#include <time.h>
#include <pthread.h>
#include <sched.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <linux/if.h>

#include "keys.h"
#include "leds.h"
#include "public.h"

#define IFNAMSIZE 16

/**
 * xy_popen - run command
 * @cmd : command
 */
int xy_popen(char * cmd)
{
    char command[512] = {0};
    FILE * fp;

    snprintf(command, sizeof(command), cmd);
    ac_traces(MSG_LEVEL_INFO, "cmd = %s, cmdlen = %d\n", command, strlen(cmd));

    fp = popen(command, "r");
    if (fp == NULL) {
        ac_traces(MSG_LEVEL_ERROR, "popen fail");
        return -1;
    }
    else 
        ac_traces(MSG_LEVEL_INFO, "popen ok");

    pclose(fp);

    return 0;
}

/**
 * xy_network_obtain - check the effective network 
 * @eth : network name
 * @ipaddr : obtain ip address
 */
static int xy_network_obtain(char * eth, char * ipaddr)
{
    int sock_fd;
    struct sockaddr_in addr;
    struct ifreq ifr;

    /* get socket file descriptor */
    if ((sock_fd = socket(PF_INET, SOCK_DGRAM, 0)) == -1) {
        ac_traces(MSG_LEVEL_ERROR, "socket create fail.");
        return -1;
    }

    /* get ip address */
    strncpy(ifr.ifr_name, eth, IFNAMSIZE);
    ifr.ifr_name[IFNAMSIZE - 1] = '\0';

    if (ioctl(sock_fd, SIOCGIFADDR, &ifr) < 0) {
        ac_traces(MSG_LEVEL_ERROR, "no such device %s\n", eth);
        return -1;
    }

    memcpy(&addr, &ifr.ifr_addr, sizeof(addr));
    strcpy(ipaddr, inet_ntoa(addr.sin_addr));
    close(sock_fd);

    return 0;
}

/**
 * xy_network_4g_effectivenes - check 4g network
 * @none
 */
int xy_network_4g_effectivenes(void)
{
    char ipaddr[32] = {0};

    xy_network_obtain("usb0", ipaddr);

    if (strlen(ipaddr) == 0) {
        ac_traces(MSG_LEVEL_INFO, "4G ip address is null");
        return false;
    }
    else {
        ac_traces(MSG_LEVEL_INFO, "4G ip address: %s\n", ipaddr);
        return true;
    }
}

/**
 * xy_network_wireless_effectivenes - check wireless network
 * @none
 */
int xy_network_wireless_effectivenes(void)
{
    char ipaddr[32] = {0};

    xy_network_obtain("wlan0", ipaddr);

    if (strlen(ipaddr) == 0) {
        ac_traces(MSG_LEVEL_INFO, "wlan ip address is null");
        return false;
    }
    else {
        ac_traces(MSG_LEVEL_INFO, "wlan ip address:%s", ipaddr);
        return true;
    }
}
